<?php

namespace Seller\Controller;

class GoodsController extends BaseController {

    private $_model = nill;

    protected function _initialize() {
        parent::_initialize();
        $this->_model = D('Goods');
    }

    public function index() {
        header("Content-type:text/html;charset=utf-8");
        $sh['keyword'] = I('get.keyword');
        $sh['sku'] = I('get.sku');
        $sh['goods_type_id'] = I('get.goods_type_id');
        $where = array();
        $cat_id = array();
        $goods_type = $this->get_goods_type_list(432);
        if (isset($this->__get['cat_id']) && $this->__get['cat_id']) {
            $cat_id = explode('-', $this->__get['cat_id']);
            if (count($cat_id) == 1) {
                $cat_id_data = array();
                if (isset($goods_type[$cat_id[0]]['list']) && $goods_type[$cat_id[0]]['list']) {
                    foreach ($goods_type[$cat_id[0]]['list'] as $key => $value) {
                        $cat_id_data[] = $value['id'];
                    }
                }
                $cat_id_data[] = $cat_id[0];
                $where['g.goods_type_id'] = array('IN', $cat_id_data);
            } else {
                $where['g.goods_type_id'] = $cat_id[1];
            }
        }
        if ($sh['keyword'] && !empty($sh['keyword'])) {
            $where['g.name'] = array('like', "%{$sh['keyword']}%");
        }
        if ($sh['earn13'] && !empty($sh['earn13'])) {
            $where['g.earn13'] = array('eq', $sh['earn13']);
        }
        if ($sh['goods_type_id'] && !empty($sh['goods_type_id'])) {
            $where['g.goods_type_id'] = array('eq', $sh['goods_type_id']);
        }

        if (I('get.show_type') == 1) {
            $where['g.customer_id'] = array('neq', $this->__seller_info['id']);
        } else if (I('get.show_type') == 2) {
            $where['g.customer_id'] = $this->__seller_info['id'];
        }

        $cat_id = array();
        //获取农产品数据
        $where['goods_type_id'] = array('in', $this->getCategory(C('CATEGORY_ID'), C('CATEGORY_ID')));

        //$where['g.customer_id'] = $this->__seller_info['id'];
        $data = D('Goods')->getList($where, $this->__row);
        //获得供货商列表
        if ($data) {
            foreach ($data['list'] as $key => $value) {
                $supply_total = M('goods_supply')->alias('gs')->join('__CUSTOMER__ c ON c.id = gs.customer_id')->where(array('goods_id' => $value['id'], 'gs.status' => 2))->count();
                $data['list'][$key]['supply_total'] = $supply_total;
                //是否已是供应商
                //$data['list'][$key]['is_supply'] = M('goods_supply')->where(array('customer_id' => $this->__seller_info['id'], 'goods_id' => $value['id']))->find() ? 1 : 0;
                //是否已是分销商
                $data['list'][$key]['attribute'] = array();
                $attribute = M('goods_attribute')
                                ->alias('ga')
                                ->join('LEFT JOIN zt_attribute as a ON a.id=ga.attribute_id')
                                ->where(array('ga.goods_id' => $value['id']))
                                ->field('ga.*,a.name')
                                ->limit(5)->select();
                if (count($attribute) > 0) {
                    $data['list'][$key]['attribute'] = $attribute;
                }
                $data['list'][$key]['is_distribution'] = M('goods_distribution')->where(array('customer_id' => $this->__seller_info['id'], 'goods_id' => $value['id'], 'type' => 1))->find() ? 1 : 0;
            }
        }
        $this->assign('data', $data);
        $this->assign('goods_type_value', (isset($this->__get['cat_id']) && $this->__get['cat_id'] ? explode('-', $this->__get['cat_id']) : array()));
        $this->assign('goods_type', $goods_type);
        $this->assign('sh', $sh);
        $this->display();
    }

    private function get_goods_type_list($pid) {
        if ($pid) {
            $goods_type = M('goods_type')->where(array('pid' => $pid))->field('id,pid,name')->select();
            if ($goods_type) {
                $data = array();
                foreach ($goods_type as $key => $value) {
                    $data[$value['id']] = $value;
                    $result = $this->get_goods_type_list($value['id']);
                    $result ? $data[$value['id']]['list'] = $result : '';
                }
            }
        }
        return $data;
    }

    /**
     * 发布产品或者供应产品之前数据完整性检测
     */
    private function _addPorductCheck() {
        if (!M('customer_warehouse')->where(array('customer_id' => $this->__seller_info['id']))->find()) {
            $this->error('非常抱歉，您还未创建仓库，必须要创建仓库之后才能发布产品', U('Warehouse/add'));
        }
        if (!M('dispatching')->where(array('customer_id' => $this->__seller_info['id']))->find()) {
            $this->error('非常抱歉，您还未创建物流配送模板，发布产品之前必须要创建物流模板');
        }
    }

    /*
     * 商品添加
     */

    public function add() {
        $this->_addPorductCheck();
        if (IS_POST) {
            $this->__post['poster']['customer_id'] = $this->__seller_info['id'];
            isset($this->__post['poster']['pic_list']) && $this->__post['poster']['pic_list'] ? $this->__post['poster']['pic_list'] = implode(',', $this->__post['poster']['pic_list']) : '';

            $this->_model->startTrans();
            if ($this->_model->create($this->__post['poster']) === false) {
                $this->_model->rollback();
                $this->error($this->_model->getError());
            }
            if (!$goods_id = $this->_model->add()) {
                $this->_model->rollback();
                $this->error('添加失败，请重新操作');
            }
            //添加商品属性信息
            if (isset($this->__post['goods_attr']) && $this->__post['goods_attr'] && is_array($this->__post['goods_attr'])) {
                $goods_attr_data = array();
                foreach ($this->__post['goods_attr'] as $k => $v) {
                    $goods_attr_data[] = array(
                        'attribute_id' => $k,
                        'goods_id' => $goods_id,
                        'data' => is_array($v) ? implode(',', $v) : $v
                    );
                }
                //属性全部添加
                M('goods_attribute')->addAll($goods_attr_data);
            }
            //添加供货信息
            $goods_supply_model = D('GoodsSupply');

            $this->__post['distribution']['customer_id'] = $this->__seller_info['id'];
            $this->__post['distribution']['goods_id'] = $goods_id;
            isset($this->__post['distribution']['sale_mode']) ? $this->__post['distribution']['sale_mode'] = ',' . implode(',', $this->__post['distribution']['sale_mode']) . ',' : '';
            $this->__post['distribution']['status'] = 0;

            //一件代发处理
            if (strpos($this->__post['distribution']['sale_mode'], ',1,') === false) {
                unset($this->__post['distribution']['acting_price']);
            }
            //批发处理
            if (strpos($this->__post['distribution']['sale_mode'], ',3,') !== false) {
                $this->__post['distribution']['wholesale_pay_rule'] = $this->__post['distribution']['wholesale_pay_type'] > 1 ? serialize($this->__post['distribution']['wholesale_pay_rule']) : '';
            } else {
                unset($this->__post['distribution']['lock_price'], $this->__post['distribution']['lock_small_price'], $this->__post['distribution']['lock_start_num'], $this->__post['distribution']['inc_lock_num'], $this->__post['distribution']['inc_lock_price']);
            }

            //锁货模式处理
            if (strpos($this->__post['distribution']['sale_mode'], ',2,') !== false) {
                $lock_pay_rule = '';
                if ($this->__post['distribution']['lock_pay_type'] == 2) {
                    unset($this->__post['distribution']['lock_pay_rule']['received']);
                    $lock_pay_rule = serialize($this->__post['distribution']['lock_pay_rule']);
                } else if ($this->__post['distribution']['lock_pay_type'] == 3) {
                    $lock_pay_rule = serialize($this->__post['distribution']['lock_pay_rule']);
                }
                $this->__post['distribution']['lock_pay_rule'] = $lock_pay_rule;
            } else {
                unset($this->__post['distribution']['wholesale_price'], $this->__post['distribution']['wholesale_start_num'], $this->__post['distribution']['inc_wholesale_num'], $this->__post['distribution']['inc_wholesale_price'], $this->__post['distribution']['wholesale_small_price']);
            }

            $this->__post['distribution']['stock_num_total'] = $this->__post['distribution']['stock_num'];
            $this->__post['distribution']['create_time'] = time();
            $this->__post['distribution']['stock_arrive_time'] = $this->__post['distribution']['stock_status'] == 2 ? strtotime($this->__post['distribution']['stock_arrive_time']) : 0;
            $this->__post['distribution']['invalid_time'] = $this->__post['distribution']['is_invalid_type'] == 2 ? strtotime($this->__post['distribution']['invalid_time']) : 0;

            $this->__post['distribution']['information'] = serialize($this->__post['poster']['information']);
            if ($goods_supply_model->create($this->__post['distribution']) === false) {
                $this->_model->rollback();
                $this->error($goods_supply_model->getError());
            }
            $goods_supply_id = $goods_supply_model->add();
            if ($goods_supply_id === false) {
                $this->_model->rollback();
                $this->error('添加失败，请重新操作');
            }
            $this->_model->commit();
            //增加库存变化日志表
            $content = "新增库存 {$this->__post['distribution']['stock_num']} , 库存总量 " . $this->__post['distribution']['stock_num'];
            M('goods_sync_stock_log')->add(
                    array('goods_supply_product_id' => $goods_supply_id, 'content' => $content)
            );
            $this->success('商品入库成功', U('Goods/index'));
        } else {
            $goods_brand = M('Goods_brand')->field('id,name')->select();
            $goods_types = M('Goods_type')->field('id,name,pid')->select();
            $country = M('country')->where(array('enabled' => 'true'))->field('country_id,Chinese_name')->select();

            $tradeList = M("Trade")->group('code')->select();


            $tree = new \Tree\Tree(M('goods_type')->field('id,pid,name')->select());
            $tree->icon = array('&nbsp;&nbsp;&nbsp;&nbsp;|', '&nbsp;&nbsp;&nbsp;&nbsp;|------------', '&nbsp;&nbsp;&nbsp;&nbsp;|-');

            $this->assign('select_option_list', $tree->get_tree(C('CATEGORY_ID'), '<option value=\$id \$selected>\$spacer\$name</option>'));
            $this->assign('country', $country);
            $this->assign('goods_brand', $goods_brand);
            $this->assign('tradeList', $tradeList);

            //获得仓库信息列表
            $this->assign('warehouse_list', M('customer_warehouse')->where(array('customer_id' => $this->__seller_info['id']))->field('id,name')->select());
            $this->display('form');
        }
    }

    public function update() {
        $m = M('goods');
        $id = I('post.id', '', 'intval');
        $data = I('post.arr');
        $pic_thumb = I('post.pic_thumb', '', 'strip_tags');

        $data['pic_thumb'] = $pic_thumb ? $pic_thumb : '';
        if ($data['info_keywords']) {
            $data['info_keywords'] = json_encode(array_unique(explode("、", $data['info_keywords'])));
        }

        if ($id) {
            $m->data($data)->where("id='{$id}'")->save();
            addlog('编辑商品，ID：' . $id);
        } else {
            $m->data($data)->add();
            addlog('新增商品，名称：' . $data['name']);
        }

        $this->success('操作成功！', U('index'));
    }

    /*
     * 商品编辑
     */

    public function edit($id = 0) {
        $id = intval($id);
        $m = M('goods');
        $goods = $m->where("id='$id'")->find();
        if (!$goods) {
            $this->error('参数错误！');
        }
        if (IS_POST) {
            isset($this->__post['poster']['pic_list']) && $this->__post['poster']['pic_list'] ? $this->__post['poster']['pic_list'] = implode(',', $this->__post['poster']['pic_list']) : '';
            $this->_model->startTrans();
            if ($this->_model->where(array('id' => $id))->save($this->__post['poster']) === false) {
                $this->_model->rollback();
                $this->error('修改失败，请重新操作');
            }
            //先删除原始数据
            M('goods_attribute')->where(array('goods_id' => $id))->delete();
            //添加商品属性信息
            if (isset($this->__post['goods_attr']) && $this->__post['goods_attr'] && is_array($this->__post['goods_attr'])) {
                $goods_attr_data = array();
                foreach ($this->__post['goods_attr'] as $k => $v) {
                    $goods_attr_data[] = array(
                        'attribute_id' => $k,
                        'goods_id' => $id,
                        'data' => is_array($v) ? implode(',', $v) : $v
                    );
                }
                //属性全部添加
                M('goods_attribute')->addAll($goods_attr_data);
            }
            $this->_model->commit();
            $this->success('商品修改成功');
        } else {
            $goods_brand = M('Goods_brand')->field('id,name')->select();
            $goods_types = M('Goods_type')->field('id,name,pid')->select();
            $country = M('country')->where(array('enabled' => 'true'))->field('country_id,Chinese_name')->select();

            $tradeList = M("Trade")->group('code')->select();
            $tree = new \Tree\Tree(M('goods_type')->field('id,pid,name')->select());
            $tree->icon = array('&nbsp;&nbsp;&nbsp;&nbsp;|', '&nbsp;&nbsp;&nbsp;&nbsp;|------------', '&nbsp;&nbsp;&nbsp;&nbsp;|-');
            $this->assign('select_option_list', $tree->get_tree(C('CATEGORY_ID'), '<option value=\$id \$selected>\$spacer\$name</option>'));
            $this->assign('tradeList', $tradeList);
            $this->assign('goods_brand', $goods_brand);
            $this->assign('country', $country);
            $this->assign('goods', $goods);
            $this->display('form');
        }
    }

    public function del() {
        $ids = isset($_REQUEST['ids']) ? $_REQUEST['ids'] : false;

        if (is_array($ids)) {
            foreach ($ids as $k => $v) {
                $ids[$k] = intval($v);
            }
            if (!$ids) {
                $this->error('参数错误！');
                $uids = implode(',', $uids);
            }
        }

        $map['id'] = array('in', $ids);
        if (M('goods')->where($map)->delete()) {
            addlog('删除商品ID：' . $ids);
            $this->success('恭喜，商品删除成功！');
        } else {
            $this->error('参数错误！');
        }
    }

    public function distribution() {
        $where['d.customer_id'] = $this->__seller_info['id'];
        $type = 1;
        if (!I('get.type') || !in_array(I('get.type'), array('lock', 'distribution')))
            $type = 1;
        if (I('get.type') == 'lock') {
            $type = 2;
			$this->assign('advent_count' , M('GoodsDistribution')->where('`stock_num` > 0 AND `storage_end_time` >= "' . date('Y-m-d H:i:s') . '" AND `storage_end_time` < "' . date('Y-m-d H:i:s' , strtotime("+{$this->__goods_advent_warning} day")) . '" AND `customer_id` = ' . $this->__seller_info['id'])->count());
            $this->assign('normal_count', M('GoodsDistribution')->where('`stock_num` > 0 AND `storage_end_time` >= "' . date('Y-m-d H:i:s') . '" AND `customer_id` = ' . $this->__seller_info['id'])->count());
            $this->assign('nothing_count', M('GoodsDistribution')->where('`stock_num` <= 0 AND `customer_id` = ' . $this->__seller_info['id'])->count());
            $this->assign('overdue_count', M('GoodsDistribution')->where('`stock_num` > 0 AND `storage_end_time` < "' . date('Y-m-d H:i:s') . '" AND `customer_id` = ' . $this->__seller_info['id'])->count());
            switch (I('status')) {
                case '2' :
                    $where['_string'] = 'd.`stock_num` <= 0';
                    break;
                case '3' :
                    $where['_string'] = 'd.`stock_num` > 0 AND d.`storage_end_time` < "' . date('Y-m-d H:i:s') . '"';
                    break;
                default :
                    $where['_string'] = 'd.`stock_num` > 0 AND d.`storage_end_time` >= "' . date('Y-m-d H:i:s') . '"';
                    break;
            }
        }
        $where['d.type'] = $type;
        $data = D('GoodsDistribution')->getList($where);
        if ($data['list']) {
            foreach ($data['list'] as $key => $value) {
                $data['list'][$key]['supply_total'] = M('goods_supply')->where(array('goods_id' => $value['goods_id'], 'status' => 2, 'stock_status' => 1))->count();
            }
        }
        $this->assign('type', $type);
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 锁货商品支付库存保管费
     * @return boolean
     */
    public function payWarehouseStorageMoney() {
        if (!isset($this->__get['id']) || intval($this->__get['id']) <= 0) {
            tipsDivError('信息错误');
        }
        $distribution_info = M('goods_distribution')->alias('gd')->join('__GOODS_SUPPLY__ gs ON gs.id = gd.goods_supply_id')->join('__GOODS__ g ON g.id = gs.goods_id')
                        ->join('__CUSTOMER_WAREHOUSE__ cw ON cw.id = gs.warehouse_id')
                        ->where(array('gd.id' => $this->__get['id']))->field('gd.id,cw.storage_overdue_rule,gd.storage_end_time,g.weight,gd.stock_num,gd.goods_supply_id')->find();
        if (!$distribution_info)
            tipsDivError('支付信息不存在');
        $distribution_info['storage_overdue_rule'] = unserialize($distribution_info['storage_overdue_rule']);
        $distribution_info['expect_price'] = goods_storage_overdue_money($distribution_info['id']);
        $distribution_info['goods_price'] = ceil($distribution_info['weight'] * $distribution_info['stock_num'] / $distribution_info['storage_overdue_rule']['weight']) * $distribution_info['storage_overdue_rule']['price'];
        $this->assign('payInfo', $this->__getCustomerPayment($distribution_info['goods_supply_id']));
        $this->assign('local_price', M('customer')->where(array('id' => $this->__seller_info['id']))->getField('money'));
        $this->assign('start_time_date', ( strtotime($distribution_info['storage_end_time']) - time() < 0 ? date("Y-m-d", strtotime('+1 day')) : date('Y-m-d', strtotime($distribution_info['storage_end_time']) + 3600 * 24)));
        $this->assign('start_time', ( strtotime($distribution_info['storage_end_time']) - time() < 0 ? date("Y-m-d") : date('Y-m-d', strtotime($distribution_info['storage_end_time']))));
        $this->assign('data', $distribution_info);
        $this->display();
    }

    /**
     * 仓库保管费支付下单
     * @return boolean
     */
    public function warehouseStorageOrder() {
        if (!isset($this->__get['id']) || intval($this->__get['id']) <= 0) {
            $this->error('信息错误');
        }
        if (isset($this->__get['pay_id']) && $this->__get['pay_id'] && intval($this->__get['id']) <= 0) {
            $this->error('支付方式错误');
        }
        if (isset($this->__get['date']) && $this->__get['date'] && !preg_match('/^[0-9]{4}\-[0-9]{1,2}\-[0-9]{1,2}$/is', $this->__get['date'])) {
            $this->error('存储时间格式错误');
        }
        $distribution_info = M('goods_distribution')->alias('gd')->join('__GOODS_SUPPLY__ gs ON gs.id = gd.goods_supply_id')->join('__GOODS__ g ON g.id = gs.goods_id')
                        ->join('__CUSTOMER_WAREHOUSE__ cw ON cw.id = gs.warehouse_id')
                        ->where(array('gd.id' => $this->__get['id']))->field('gd.id,cw.storage_overdue_rule,gd.storage_end_time,g.weight,gd.stock_num,gd.goods_supply_id')->find();
        if (!$distribution_info)
            $this->error('支付信息不存在');
        if (strtotime($distribution_info['storage_end_time']) - time() < 0) {
            $start_time = time();
        } else {
            $start_time = strtotime($distribution_info['storage_end_time']);
        }
        if (strtotime($this->__get['date']) < $start_time) {
            $this->error('存储日期错误');
        }
        $distribution_info['storage_overdue_rule'] = unserialize($distribution_info['storage_overdue_rule']);
        $pay_price = goods_storage_overdue_money($distribution_info['id']); //需要支付的金额
        $day_price = ceil($distribution_info['weight'] * $distribution_info['stock_num'] / $distribution_info['storage_overdue_rule']['weight']) * $distribution_info['storage_overdue_rule']['price'];
        $day_num = ceil(( strtotime($this->__get['date']) - $start_time ) / ( 24 * 3600 ));
        $add_data = array(
            'day_time' => $this->__get['date'],
            'payment_id' => $this->__get['pay_id'],
            'customer_id' => $this->__seller_info['id'],
            'goods_distribution_id' => $this->__get['id'],
            'sn' => time() . rand(100, 999),
            'price' => $pay_price + ( $day_num * $day_price )
        );
        if ($order_id = M('warehouse_storage_order')->add($add_data)) {
            exit(json_encode(array('info' => '下单成功', 'status' => 1, 'data' => $order_id)));
        } else {
            $this->error('下单失败，请重新下单');
        }
    }

    public function addOrder() {
        $good_id = I('get.goods_id');
        $info = M('goods')
                ->where(array('id' => $good_id))
                ->find();
        $distribution_stock = M('goods_distribution')->where(array('goods_id' => $info['id'], 'customer_id' => $this->__seller_info['id'], 'stock_status' => 1, 'stock_num' => array('gt', 0)))->sum('stock_num');
        $stock_num = M('goods_supply')->where(array('goods_id' => $info['id'], 'stock_status' => 1, 'stock_num' => array('gt', 0)))->sum('stock_num');
        $info['min_price'] = M('goods_supply')->where(array('goods_id' => $info['id'], 'stock_status' => 1, 'stock_num' => array('gt', 0)))->order('acting_price')->getField('acting_price');
        $info['max_price'] = M('goods_supply')->where(array('goods_id' => $info['id'], 'stock_status' => 1, 'stock_num' => array('gt', 0)))->order('acting_price desc')->getField('acting_price');

        $info['stock_num'] = $distribution_stock + $stock_num;

        if ($info['stock_num'] == 0) {
            $this->error('库存不足');
            return false;
        }
        $area = M('area')->where(array('parentid' => 0))->select();
        $address = M('address')->alias('ad')
                ->join('LEFT JOIN zt_area as a  ON a.areaid = ad.city_id')
                ->where(array('customer_id' => $this->__seller_info['id']))
                ->field('ad.*,a.areaname')
                ->select();
        $this->assign('area', $area);
        $this->assign('address', $address);
        $this->assign('info', $info);
        $this->display();
    }

    /**
     * 获得产品供应商列表
     */
    public function goodsSupplyList() {
        if (!isset($this->__get['goods_id']) || intval($this->__get['goods_id']) <= 0) {
            $this->ajaxReturn(array('status' => 0));
        }
        $supply_info = M('goods_supply')->alias('gs')->join('__CUSTOMER__ c ON c.id = gs.customer_id')->field('c.shop_name,gs.acting_price,gs.lock_price,gs.wholesale_price,gs.market_price,gs.price,gs.stock_num,gs.id,gs.stock_status')->page($this->__page, 3)->where(array('gs.goods_id' => $this->__get['goods_id'], 'gs.status' => 2))->select();
        if ($supply_info) {
            foreach ($supply_info as $key => $value) {
                $supply_info[$key]['is_buy'] = M('goods_distribution')->where(array('customer_id' => $this->__seller_info['id'], 'type' => 2, 'goods_supply_id' => $value['id']))->find() ? 1 : 0;
                $supply_info[$key]['url'] = U('Goods/goodsLockStock', array('id' => $value['id']));
            }
            $data = array('status' => 1, 'data' => $supply_info);
        } else {
            $data = array('status' => 0);
        }
        $this->ajaxReturn($data);
    }

    /**
     * 商家分销产品
     */
    public function productDistribution() {
        if (IS_POST) {
            if (!isset($this->__post['goods_id']) || intval($this->__post['goods_id']) <= 0)
                $this->error('分销商品信息不能为空');
            if (!isset($this->__post['market_price']) || !checkMoney($this->__post['market_price']))
                $this->error('市场价格式错误');
            if (!isset($this->__post['price']) || !checkMoney($this->__post['price']))
                $this->error('分销金额错误');
            $goods_info = M('goods')->find($this->__post['goods_id']);
            if (!$goods_info)
                $this->error('产品信息错误');
            $data = array(
                'customer_id' => $this->__seller_info['id'],
                'goods_id' => $goods_info['id'],
                //'goods_supply_id' => $supply_info['id'],
                //'supply_customer_id' => $supply_info['customer_id'],
                'market_price' => $this->__post['market_price'],
                'cost_price' => $supply_info['acting_price'],
                'price' => $this->__post['price'],
                'create_time' => date('Y-m-d H:i:s')
            );
            if (M('goods_distribution')->create($data) === false) {
                $this->error('数据组合错误，请重试');
            }
            if (M('goods_distribution')->add() === false) {
                $this->error('产品分销失败，请重试');
            }
            $this->success('产品分销成功');
        } else {
            if (!isset($this->__get['id']) || intval($this->__get['id']) <= 0) {
                tipsDivError('信息错误');
            }
            $info = M('goods')->field('earn13,name,id')->find($this->__get['id']);
            if (M('goods_distribution')->where(array('customer_id' => $this->__seller_info['id'], 'goods_id' => $this->__get('id')))->find()) {
                tipsDivError('您已经分销过此产品请勿重复分销');
            }
            //获得供应商家总数
            $supply_goods_total = M('goods_supply')->where(array('goods_id' => $this->__get['id']))->count();
            //获得市场价区间
            $info['market_price'] = $supply_goods_total <= 0 ? '无报价' : ($this->_formatPriceStyle(M('goods_supply')->where(array('goods_id' => $info['id']))->order('id ASC')->getField('market_price')) . '- ' . $this->_formatPriceStyle(M('goods_supply')->where(array('goods_id' => $info['id']))->order('id DESC')->getField('market_price')));
            //建议销售价
            $info['price'] = $supply_goods_total <= 0 ? '无报价' : ( $this->_formatPriceStyle(M('goods_supply')->where(array('goods_id' => $info['id']))->order('id ASC')->getField('price')) . ' - ' . $this->_formatPriceStyle(M('goods_supply')->where(array('goods_id' => $info['id']))->order('id DESC')->getField('price')) );
            //成本价
            $info['acting_price'] = $supply_goods_total <= 0 ? '无报价' : ( $this->_formatPriceStyle(M('goods_supply')->where(array('goods_id' => $info['id']))->order('id ASC')->getField('acting_price')) . ' - ' . $this->_formatPriceStyle(M('goods_supply')->where(array('goods_id' => $info['id']))->order('id DESC')->getField('acting_price')) );
            //所有供应商库存
            $info['stock_num'] = $supply_goods_total <= 0 ? '无库存' : M('goods_supply')->where(array('goods_id' => $info['id']))->getField('stock_num');
            $this->assign('info', $info);
            $this->assign('supply_goods_total', $supply_goods_total);
            $this->display();
        }
    }

    private function _formatPriceStyle($price) {
        return "<span style='font-size:10px;'>￥</span><span style='font-size:16px;'>{$price}</span>";
    }

    /**
     * 商品锁库
     */
    public function goodsLockStock() {
        if (IS_POST) {
            if (!isset($this->__post['supply_id']) || intval($this->__post['supply_id']) <= 0)
                $this->error('分销商品信息不能为空');
            if (!isset($this->__post['market_price']) || !checkMoney($this->__post['market_price']))
                $this->error('市场价格式错误');
            if (!isset($this->__post['price']) || !checkMoney($this->__post['price']))
                $this->error('分销金额错误');
            $supply_info = M('goods_supply')->alias('gs')->join('__CUSTOMER_WAREHOUSE__ cw ON cw.id = gs.warehouse_id')->where(array('gs.id' => $this->__post['supply_id']))->field('gs.*,cw.supply_send_day')->find();
            if (!$supply_info)
                $this->error('产品信息错误');
            if (!isset($this->__post['stock_num']) || intval($this->__post['stock_num']) <= 0 || $this->__post['stock_num'] > $supply_info['stock_num'])
                $this->error('库存错误');
            if ($this->__post['stock_num'] < $supply_info['lock_start_num']) {
                $this->error('库存必须大于最低锁货量');
            }
            //组合分销的数据
            $data = array(
                'customer_id' => $this->__seller_info['id'],
                'goods_id' => $supply_info['goods_id'],
                'goods_supply_id' => $supply_info['id'],
                'supply_customer_id' => $supply_info['customer_id'],
                'market_price' => $this->__post['market_price'],
                'cost_price' => lock_goods_price($supply_info['id'], $this->__post['stock_num']),
                'price' => $this->__post['price'],
                'pay_rule' => $supply_info['lock_pay_rule'],
                'stock_status' => $supply_info['stock_status'],
                'storage_end_time' => date('Y-m-d H:i:s', strtotime('+' . $supply_info['supply_send_day'] . ' day')),
                'create_time' => date('Y-m-d H:i:s')
            );
            $data['stock_num'] = $this->__post['stock_num'];
            $data['type'] = 2; //设置锁货模式
            //锁库订单数据组合
            $log_data = array(
                'customer_id' => $this->__seller_info['id'],
                'sn' => date('mHis') . rand(10000, 99999),
                'goods_supply_id' => $supply_info['id'],
                'cusomter_supply_id' => $supply_info['customer_id'],
                'stock_num' => $data['stock_num'],
                'single_price' => $data['cost_price'],
                'total_price' => $data['cost_price'] * $data['stock_num'],
                'orgin_data' => serialize($data),
                'create_time' => date('Y-m-d H:i:s')
            );
            //数据入库
            $inert_id = M('order_goods_distribution_lock')->add($log_data);
            if ($inert_id === false) {
                $this->error('下单失败，请重试');
            }
            //修改获得订单因支付金额
            M('order_goods_distribution_lock')->save(array('id' => $inert_id, 'pay_total_price' => lock_order_pay_price($inert_id)));
            $this->success('下单成功请立即去支付', U('LockOrder/detail', array('sn' => $log_data['sn'])));
        } else {
            if (!isset($this->__get['id']) || intval($this->__get['id']) <= 0) {
                tipsDivError('信息错误');
            }
            $supply_info = M('goods_supply')->alias('gs')->join("__GOODS__ g ON g.id = gs.goods_id")->join('__CUSTOMER__ c ON c.id = gs.customer_id')->where(array('gs.id' => $this->__get['id']))
                            ->field('c.shop_name,g.name,g.earn13,gs.market_price,gs.price,gs.lock_price,gs.lock_start_num,gs.stock_num,gs.id,gs.stock_status,gs.stock_arrive_time')->find();
            if (!$supply_info) {
                tipsDivError('供应产品信息不存在');
            }
            $this->assign('info', $supply_info);
            $this->display();
        }
    }

    /**
     * 库存供应
     */
    public function supplyCommodity() {
        $this->_addPorductCheck();
        if (IS_POST) {
            $data = $this->__post['poster'];
            if (!isset($data['goods_id']) || intval($data['goods_id']) <= 0)
                $this->error('商品ID格式错误');
            if (!isset($data['market_price']) || !checkMoney($data['market_price']))
                $this->error('市场价格式错误');
            if (!isset($data['acting_price']) || !checkMoney($data['acting_price']))
                $this->error('一件代发价格式错误');
            if (!isset($data['lock_price']) || !checkMoney($data['lock_price']))
                $this->error('锁货价格式错误');
            if (!isset($data['lock_start_num']) || $data['lock_start_num'] <= 0)
                $this->error('最低锁货量式错误');
            if (!isset($data['wholesale_price']) || !checkMoney($data['wholesale_price']))
                $this->error('批发价格式错误');
            if (!isset($data['wholesale_start_num']) || $data['wholesale_start_num'] <= 0)
                $this->error('最低批发量式错误');
            if (!isset($data['price']) || !checkMoney($data['price']))
                $this->error('建议销售金额错误');
            if (!isset($data['stock_num']) || intval($data['stock_num']) <= 0)
                $this->error('供应库存格式错误');
            if (!isset($data['warehouse_id']) || !is_numeric($data['warehouse_id']))
                $this->error('仓库数据错误');
            $data['customer_id'] = $this->__seller_info['id'];
            $data['status'] = 0;
            $data['stock_num_total'] = $data['stock_num'];
            $data['create_time'] = time();
            $data['end_time'] = strtotime($data['end_time']);
            $data['stock_arrive_time'] = $data['stock_status'] == 2 ? strtotime($data['stock_arrive_time']) : 0;
            $data['invalid_time'] = $data['is_invalid_type'] == 2 ? strtotime($data['invalid_time']) : 0;
            //批发处理
            if (strpos($data['sale_mode'], ',3,') !== false) {
                $data['wholesale_pay_rule'] = $data['wholesale_pay_rule'] > 1 ? serialize($data['wholesale_pay_rule']) : '';
            } else {
                unset($data['wholesale_price'],$data['wholesale_start_num'], $data['inc_wholesale_num'], $data['inc_wholesale_price'], $data['wholesale_small_price']);
            }

            //锁货模式处理
            if (strpos($data['sale_mode'], ',2,') !== false) {
                $lock_pay_rule = '';
                if ($data['lock_pay_type'] == 2) {
                    unset($data['lock_pay_rule']['received']);
                    $lock_pay_rule = serialize($data['lock_pay_rule']);
                } else if ($data['lock_pay_type'] == 3) {
                    $lock_pay_rule = serialize($data['lock_pay_rule']);
                }
                $data['lock_pay_rule'] = $lock_pay_rule;
            } else {
                unset($data['lock_price'], $data['lock_small_price'], $data['lock_start_num'], $data['inc_lock_num'], $data['inc_lock_price']);
            }
            if (M('goods_supply')->create($data) === false) {
                $this->error('数据组合错误，请重试');
            }
            $goods_supply_id = M('goods_supply')->add();
            if ($goods_supply_id === false) {
                $this->error('供应失败，请重试');
            }
            //增加库存变化日志表
            $content = "新增库存 {$data['stock_num']} , 库存总量 " . $data['stock_num'];
            M('goods_sync_stock_log')->add(
                    array('goods_supply_product_id' => $goods_supply_id, 'content' => $content)
            );
            $this->success('供应产品信息提交成功，请等待审核', U('Goods/supplyGoodsList'));
        } else {
            if (!isset($this->__get['id']) || intval($this->__get['id']) <= 0) {
                $this->error('供应数据有误');
            }
            //判断是否已经供应
            /* if ($supplu_info = M('goods_supply')->where(array('goods_id' => $this->__get['id'], 'customer_id' => $this->__seller_info['id']))->find()) {
              $this->error('您已有供货数据，请在供货清单里面查看');
              } */

            //获得仓库信息列表
            $this->assign('warehouse_list', M('customer_warehouse')->where(array('customer_id' => $this->__seller_info['id']))->field('id,name')->select());
            $goods_info = M('Goods')->field('id,name,earn13')->find($this->__get['id']);
            $this->assign('goods_info', $goods_info);
            $this->display();
        }
    }

    /**
     * 供应清单
     */
    public function supplyGoodsList() {
        $model = M('GoodsSupply');
        $where = array('gs.customer_id' => $this->__seller_info['id']);
        switch (I('get.status')) {
            case '2' :
                $where['gs.stock_num'] = array('ELT', $this->__goods_stock_warning);
                break;
            case '3' :
                $where['gs.stock_status'] = 2;
                break;
        }
        $total = $model->alias('gs')->where($where)->count();
        $list = $model->alias('gs')->join('__GOODS__ g ON g.id = gs.goods_id')->where($where)->field('gs.*,g.name,g.earn13,g.customer_id')->page($this->__page, $this->__row)->order('gs.id DESC')->select();
        $this->__assignPage($total);
        if ($list) {
            foreach ($list as $key => $value) {
                $list[$key]['total'] = M('goods_distribution')->where(array('goods_supply_id' => $value['id']))->count();
                $distribution_stock_total = M('goods_distribution')->where(array('goods_supply_id' => $value['id']))->sum('stock_num');
                $list[$key]['distribution_stock_num'] = !$distribution_stock_total ? 0 : $distribution_stock_total;
            }
        }
        $this->assign('all_total', M('goods_supply')->where(array('customer_id' => $this->__seller_info['id']))->count());
        $this->assign('notice_total', M('goods_supply')->where("customer_id = {$this->__seller_info['id']} AND stock_num < {$this->__goods_stock_warning}")->count());
        $this->assign('transport_total', M('goods_supply')->where(array('customer_id' => $this->__seller_info['id'], 'stock_status' => 2))->count());
        $this->assign('lists', $list);
        $this->display();
    }

    /**
     * 增加供应库存
     */
    public function incStockNum() {
        if (IS_POST) {
            if (!isset($this->__post['id']) || intval($this->__post['id']) <= 0)
                $this->error('供应产品信息错误');
            if (!isset($this->__post['stock_num']) || intval($this->__post['stock_num']) <= 0)
                $this->error('库存数量不正确');
            if (!isset($this->__post['market_price']) || !checkMoney($this->__post['market_price']))
                $this->error('市场价格式错误');
            if (!isset($this->__post['acting_price']) || !checkMoney($this->__post['acting_price']))
                $this->error('一键代发价格式错误');
            if (!isset($this->__post['lock_price']) || !checkMoney($this->__post['lock_price']))
                $this->error('锁货价格式错误');
            if (!isset($this->__post['price']) || !checkMoney($this->__post['price']))
                $this->error('建议销售金额错误');
            if (!isset($this->__post['warehouse_id']) || !is_numeric($this->__post['warehouse_id']))
                $this->error('仓库数据错误');
            $type = $this->__post['type'] == 1 ? 1 : 2;
            $this->__post['wholesale_pay_rule'] = $this->__post['wholesale_pay_type'] > 1 ? serialize($this->__post['wholesale_pay_rule']) : '';
            if ($this->__post['lock_pay_type'] == 1) {
                $lock_pay_rule = '';
            } else if ($this->__post['lock_pay_type'] == 2) {
                unset($this->__post['lock_pay_rule']['received']);
                $lock_pay_rule = serialize($this->__post['lock_pay_rule']);
            } else if ($this->__post['lock_pay_type'] == 3) {
                $lock_pay_rule = serialize($this->__post['lock_pay_rule']);
            }
            $this->__post['lock_pay_rule'] = $lock_pay_rule;
            //查询以及认证信息合法
            $find_info = M('goods_supply')->where(array('id' => $this->__post['id'], 'customer_id' => $this->__seller_info['id']))->find();
            if (!$find_info)
                $this->error('修改的供应产品信息不存在');
            if ($type == 2 && $find_info['stock_num'] < $this->__post['stock_num']) {
                $this->error('减少库存不能比销售库存大');
            }
            //获得修改的库存
            $stock_num = $type == 2 ? ( $find_info['stock_num'] - $this->__post['stock_num'] <= 0 ? 0 : $find_info['stock_num'] - $this->__post['stock_num'] ) : $find_info['stock_num'] + $this->__post['stock_num'];

            //修改库存
            if (M('goods_supply')->where(array('id' => $this->__post['id'], 'customer_id' => $this->__seller_info['id']))->save(array('stock_num' => $stock_num, 'warehouse_id' => $this->__post['warehouse_id'], 'price' => $this->__post['price'], 'acting_price' => $this->__post['acting_price'], 'lock_start_num' => $this->__post['lock_start_num'], 'lock_price' => $this->__post['lock_price'], 'wholesale_price' => $this->__post['wholesale_price'], 'wholesale_start_num' => $this->__post['wholesale_start_num'], 'market_price' => $this->__post['market_price']))) {
                //增加库存变化日志表
                $content = "原始可用库存 {$find_info['stock_num']} ， 新增库存 {$this->__post['stock_num']} , 库存重量 " . ( $this->__post['stock_num'] + $find_info['stock_num'] );
                //判断库存是否是减少操作
                if ($type == 2) {
                    $content = "原始可用库存 {$find_info['stock_num']} ， 减少库存 {$this->__post['stock_num']} , 库存重量 " . ( $find_info['stock_num'] - $this->__post['stock_num'] );
                }
                M('goods_sync_stock_log')->add(
                        array('goods_supply_product_id' => $this->__post['id'], 'content' => $content)
                );
                $this->success('库存更新成功', U('Goods/supplyGoodsList'));
            } else {
                $this->error('操作失败');
            }
        } else {
            if (!isset($this->__get['id']) || intval($this->__get['id']) <= 0)
                $this->error('供应产品信息错误');
            //获得仓库信息列表
            $this->assign('warehouse_list', M('customer_warehouse')->where(array('customer_id' => $this->__seller_info['id']))->field('id,name')->select());
            $info = M('goods_supply')->alias('gs')->join('__GOODS__ g ON g.id = gs.goods_id')->where(array('gs.id' => $this->__get['id'], 'gs.customer_id' => $this->__seller_info['id']))->field('gs.*,g.name,g.earn13')->find();
            $this->assign('info', $info);
            $this->display();
        }
    }

    /**
     * 查看库存日志
     */
    public function showStockLogList() {
        if (!isset($this->__get['id']) || intval($this->__get['id']) <= 0)
            $this->error('供应产品信息错误');
        $find_info = M('goods_supply')->where(array('id' => $this->__get['id'], 'customer_id' => $this->__seller_info['id']))->find();
        if (!$find_info)
            $this->error('修改的供应产品信息不存在');
        //查询列表
        $list = M('goods_sync_stock_log')->where(array('goods_supply_product_id' => $this->__get['id']))->order('id DESC')->select();
        $this->assign('lists', $list);
        $this->display();
    }

    public function order_btn() {
        $goods_id = $this->__get['goods_id'];
        $info = M('goods')
                ->where(array('id' => $goods_id))
                ->find();
        $distribution_stock = M('goods_distribution')->where(array('goods_id' => $info['id'], 'customer_id' => $this->__seller_info['id'], 'stock_status' => 1, 'stock_num' => array('gt', 0), 'type' => 2, 'storage_end_time' => array('gt', date('Y-m-d H:i:s'))))->sum('stock_num');
        $stock_num = M('goods_supply')->where(array('goods_id' => $info['id'], 'stock_num' => array('gt', 0)))->sum('stock_num');
        $info['order_type'] = 1;
        $info['stock_sum'] = $stock_num + $distribution_stock;
        //锁货库
        $info['distribution_stock'] = $distribution_stock;
        $distribution = M('goods_distribution')->where(array('goods_id' => $info['id'], 'customer_id' => $this->__seller_info['id'], 'stock_status' => 1, 'stock_num' => array('gt', 0), 'type' => 2, 'storage_end_time' => array('gt', date('Y-m-d H:i:s'))))->select();



        //供货库
        $supplys = M('goods_supply')->where(array('goods_id' => $info['id'], 'stock_status' => 1, 'status' => 2, 'stock_num' => array('gt', 0)))->order('acting_price')->select();

        $addInfo = M('address')->alias('ad')
                ->join('LEFT JOIN zt_area as a  ON a.areaid = ad.city_id')
                ->where(array('id' => $this->__get['address_id']))
                ->field('ad.*,a.areaname')
                ->find();
        if (IS_POST) {
            if (!$_POST['address_id']) {
                $this->error('收货地址不能为空');
                return false;
            }
            $receive_info = $addInfo['truename'] . '||' . $addInfo['phone'] . '|中国|' . $addInfo['areaname'] . '|||' . $addInfo['address'];
            $total = 0;
            $order_line = array();
            $fee = 0;
            $number = 0;
            /**
             * 锁货订单总价
             */
            foreach ($this->__post['distribution'] as $k => $v) {
                $dl = array();
                if ($v['number'] > 0) {
                    $deInfo = M('goods_distribution')->where(array('id' => $k))->find();
                    if ($v['number'] > $deInfo['stock_num']) {
                        $this->error('库存不足！');
                        exit;
                    }
                    $total+=($deInfo['cost_price'] * $v['number']);
                    $dl['sub_total'] = $deInfo['cost_price'] * $v['number'];
                    $dl['price'] = $deInfo['cost_price'];
                    $dl['num'] = $v['number'];
                    $number += $v['number'];
                    $dl['sub_total_untaxed'] = $deInfo['cost_price'] * $v['number'];
                    $dl['supply_price'] = $deInfo['cost_price'];
                    $dl['distribution_product_id'] = $k;
                    $dl['source_type'] = 1;
                    $dl['supply_product_id'] = $deInfo['goods_supply_id'];

                    if ($deInfo['customer_id'] == $this->__seller_info['id']) {
                        if (empty($deInfo)) {
                            $dl['pay_status'] = 2;
                        } else {
                            $dl['pay_status'] = 1;
                        }
                    }
                    if ($v['dispatching_id'] > 0) {
                        $dl['dispatching_id'] = $v['dispatching_id'];
                        $f = M('dispatching')->where(array('id' => $v['dispatching_id'], 'customer_id' => $deInfo['supply_customer_id']))->find();
                        if ($v['number'] > $f['first_num'] && $f['first_num'] > 0) {
                            $dl['fee'] = $f['first_price'] + ceil(($v['number'] - $f['first_num']) / $f['add_first_num']) * $f['add_first_price'];
                        } else {
                            $dl['fee'] = $f['first_price'];
                        }
                        $fee+=$dl['fee'];
                        $total += $dl['fee'];
                        //} else {
                        //$this->error('商品无物流方式，不能购买，请重新选择！');
                        //die;
                    }
                    $dl['supply_customer_id'] = $deInfo['supply_customer_id'];
                    $order_line[] = $dl;
                }
            }

            foreach ($this->__post['supply'] as $k => $v) {  //计算供货订单总价
                $ol = array();
                if ($v['number'] > 0) {
                    $suInfo = M('goods_supply')->where(array('id' => $k))->find();
                    if ($v['number'] > $suInfo['stock_num']) {
                        $this->error('库存不足！');
                        exit;
                    }
                    $suInfo['acting_price'] = wholesale_goods_price($k, $v['number']);
                    $total+=($suInfo['acting_price'] * $v['number']);
                    $ol['sub_total'] = $suInfo['acting_price'] * $v['number'];
                    $ol['price'] = $suInfo['acting_price'];
                    $ol['num'] = $v['number'];
                    $number += $v['number'];
                    $ol['sub_total_untaxed'] = $suInfo['acting_price'] * $v['number'];
                    $ol['supply_price'] = $suInfo['acting_price'];
                    $ol['supply_product_id'] = $k;
                    $ol['source_type'] = 2;
                    if ($suInfo['customer_id'] == $this->__seller_info['id']) {
                        $ol['pay_status'] = 2;
                    }
                    if ($v['dispatching_id'] > 0) {
                        $ol['dispatching_id'] = $v['dispatching_id'];
                        $f = M('dispatching')->where(array('id' => $v['dispatching_id'], 'customer_id' => $suInfo['customer_id']))->find();
                        if ($v['number'] > $f['first_num'] && $f['first_num'] > 0) {
                            $ol['fee'] = $f['first_price'] + ceil(($v['number'] - $f['first_num']) / $f['add_first_num']) * $f['add_first_price'];
                        } else {
                            $ol['fee'] = $f['first_price'];
                        }
                        $fee+=$ol['fee'];
                        $total += $ol['fee'];
                        //} else {
                        //$this->error('商品无物流方式，不能购买，请重新选择！');
                        //die;
                    }
                    $ol['supply_customer_id'] = $suInfo['customer_id'];
                    $order_line[] = $ol;
                }
            }
            //判断商品总数是否大于0
            if ($number <= 0) {
                $this->error('商品数量不能为0');
                die;
            }
            if ($total <= 0) {
                $this->error('商品总价不能小于0');
                die;
            }
            $data = array(
                'date_order' => date('Y-m-d H:i:s'),
                'ref' => date('YmdHis') . rand(10, 99),
                'distribution_customer_id' => $this->__seller_info['id'],
                'buyer' => $this->__seller_info['username'],
                'create_time' => date('Y-m-d H:i:s'),
                'receive_info' => $receive_info,
                'amount_total' => $total,
                'status' => 1,
                'delivery_fee' => $fee,
                'discount' => 0,
                'express_send_type' => $this->__post['chose']==1 ? ($this->__post['chose1'] ? $this->__post['chose1'] : 0) : 0,
            );

            if ($order_id = M('order')->add($data)) {


                //订单生成
                foreach ($order_line as $key => $val) {

                    $val['order_id'] = $order_id;
                    $val['ref'] = $data['ref'];
                    $val['goods_id'] = $info['id'];
                    $val['name'] = $info['name'];
                    $val['create_time'] = date('Y-m-d H:i:s');
                    $val['date_order'] = $data['date_order'];
                    if (M('order_line')->add($val)) {
                        if ($val['distribution_product_id'] > 0) {
                            hotSortNumSave($val['goods_id']);
                            M('goods_distribution')->where(array('id' => $val['distribution_product_id']))->setDec('stock_num', $val['num']); //分销商锁定库存 
                            M('goods_supply')->where(array('id' => $val['goods_supply_id']))->setInc('lock_stock_num', $val['num']); //共享库锁定库存
                        }
                        if ($val['supply_product_id'] > 0) {
                            hotSortNumSave($val['goods_id']);
                            M('goods_supply')->where(array('id' => $val['supply_product_id']))->setDec('stock_num', $val['num']); //共享库库存-
                            M('goods_supply')->where(array('id' => $val['supply_product_id']))->setInc('lock_stock_num', $val['num']); //共享库锁定库存
                        }
                    }
                }

                //orders 订单支付状态
                $orderList = M('order_line')->where(array('ref' => $data['ref']))->count();
                $orderStatus = M('order_line')->where(array('ref' => $data['ref'], 'pay_status' => 2))->count();
                if ($orderList == $orderStatus && $orderStatus > 0) {
                    M('order')->where(array('ref' => $data['ref']))->save(array('pay_status' => 2));
                } else if ($orderList > $orderStatus && $orderStatus > 0) {
                    M('order')->where(array('ref' => $data['ref']))->save(array('pay_status' => 1));
                } else {
                    M('order')->where(array('ref' => $data['ref']))->save(array('pay_status' => 0));
                }

                //查看当前分销商是否分享该商品

                if ((M('goods_distribution')->where(array('customer_id' => $this->__seller_info['id'], 'goods_id' => $info['id']))->count()) == 0 && $stock_num > 0) {
                    M('goods_distribution')->add(array('goods_id' => $info['id'], 'customer_id' => $this->__seller_info['id'], 'create_time' => date('Y-m-d H:i:s', time())));
                }
                get_order_pay_model($order_id);

                //检测订单是否没有钱需要支付 没有这更改大状态
                $order_pay_count = M('order_line')->alias('ol')->join("__ORDER_LINE_PAY__ olp ON ol.id = olp.order_line_id")->where(array('ol.order_id' => $order_id))->count();
                if ($order_pay_count <= 0) {
                    M('order')->where(array('id' => $order_id))->save(array('status' => 1, 'pay_status' => 2));
                    M('order_line')->where(array('order_id' => $order_id))->save(array('status' => 1));
                }
//判断是否在线发布物流单子
                if($data['express_send_type']==1){
                    $this->success('订单提交成功', U('Express/add', array('ref' => $data['ref'])));
                }else{
                    $this->success('订单提交成功', U('Order/detail', array('type' => 'fx', 'ref' => $data['ref'])));
                }
            } else {
                $this->error('订单提交失败');
            }
        } else {
            if ($info['stock_sum'] <= 0 || $info['stock_sum'] < $this->__get['number']) {
                $this->error('库存不够！');
            }
            $supplys = M('goods_supply')->where(array('goods_id' => $info['id'], 'stock_status' => 1, 'stock_num' => array('gt', 0)))->order('acting_price')->select();
            $num = 0;
            $info['d_max_num'] = 0; //最后参数
            $info['d_max_key'] = 0;
            $min_num = 0;
            if ($distribution_stock <= $this->__get['number']) {
                $min_num = $this->__get['number'] - $distribution_stock; //减去锁货库存
            }
            if ($distribution_stock > 0) {  //锁货库存
                foreach ($distribution as $key => $val) {
                    $suppleyOne = M('goods_supply')->where(array('id' => $val['goods_supply_id']))->find();
                    $where['customer_id'] = $suppleyOne['customer_id'];
                    $pList = M('dispatching')->where($where)->select();
                    //配送地址
                    $where['city_id'] = array('like', "%,{$addInfo['city_id']},%");

                    //查询商品关联的仓库物流

                    if ($suppleyOne['warehouse_id'] > 0) { //是否有仓库ID 
                        $tel = $where;
                        $tel['warehouse_id'] = array('like', "%,{$val['warehouse_id']},%");
                        $pList = M('dispatching')->where($tel)->select();
                        foreach ($pList as $k => $v) {
                            $wuliu_list[$v['id']] = $v;
                        }
                    }
                    //查询无仓库绑定的物流
                    if ($suppleyOne['warehouse_id'] == 0) {
                        $tel1 = $where;
                        $tel1['warehouse_id'] = '';
                        $pList = M('dispatching')->where($tel1)->select();
                        foreach ($pList as $k => $v) {
                            $wuliu_list[$v['id']] = $v;
                        }
                    }
                    //查询商品绑定的物流
                    $tel2 = $where;
                    $tel2['goods'] = array('like', "%,{$val['goods_id']},%");
                    $pList = M('dispatching')->where($tel2)->select();
                    foreach ($pList as $k => $v) {
                        $wuliu_list[$v['id']] = $v;
                    }
                    //查询物流无绑定商品的物流信息
                    $tel3 = $where;
                    $tel3['goods'] = '';
                    $pList = M('dispatching')->where($tel3)->select();
                    foreach ($pList as $k => $v) {
                        $wuliu_list[$v['id']] = $v;
                    }
                    $distribution[$key]['dispatching'] = $wuliu_list;


                    /**
                     * 求出分销最后库存数量
                     */
                    if ($num < $this->__get['number']) {
                        $num+=$val['stock_num'];
                        if ($min_num == 0 && $num > $this->__get['number']) {
                            $info['d_max_num'] = $val['stock_num'] - ($num - $this->__get['number']);
                        } else {
                            $info['d_max_num'] = $val['stock_num'];
                        }
                        $info['d_max_key'] = $key;
                    } else {
                        continue;
                    }
                }
            }

            $num = 0;
            $info['max_num'] = 0; //最后参数
            foreach ($supplys as $key => $val) {
                $where['customer_id'] = $val['customer_id'];
                $where['city_id'] = array('like', "%,{$addInfo['city_id']},%");
                $wuliu_list = array(); //物流列表
                //查询商品关联的仓库物流

                if ($val['warehouse_id'] > 0) { //是否有仓库ID 
                    $tel = $where;
                    $tel['warehouse_id'] = array('like', "%,{$val['warehouse_id']},%");

                    $pList = M('dispatching')->where($tel)->select();

                    foreach ($pList as $k => $v) {
                        $wuliu_list[$v['id']] = $v;
                    }
                }
                //查询无仓库绑定的物流
                if ($val['warehouse_id'] == 0) {
                    $tel1 = $where;
                    $tel1[''] = '';
                    $pList = M('dispatching')->where($tel1)->select();

                    foreach ($pList as $k => $v) {
                        $wuliu_list[$v['id']] = $v;
                    }
                }
                //查询商品绑定的物流
                $tel2 = $where;
                $tel2['goods'] = array('like', "%,{$val['goods_id']},%");
                $pList = M('dispatching')->where($tel2)->select();
                foreach ($pList as $k => $v) {
                    $wuliu_list[$v['id']] = $v;
                }
                //查询物流无绑定商品的物流信息
                $tel3 = $where;
                $tel3['goods'] = '';
                $pList = M('dispatching')->where($tel3)->select();

                foreach ($pList as $k => $v) {
                    $wuliu_list[$v['id']] = $v;
                }
                $supplys[$key]['dispatching'] = $wuliu_list;


                //查看是否有配送地址 没有就删除供货商
                if(count($supplys[$key]['dispatching'])==0){
                    unset($supplys[$key]);
                    continue;
                }
                if ($num < $min_num && $min_num > 0) {
                    $supplys[$key]['acting_price'] = wholesale_goods_price($val['id'], $val['stock_num']);
                    $num+=$val['stock_num'];
                    if ($min_num > 0 && $num >= $min_num) {
                        $info['max_num'] = $val['stock_num'] - ($num - $min_num);
                        $supplys[$key]['acting_price'] = wholesale_goods_price($val['id'], $info['max_num']);
                    }
                    $info['max_key'] = $key;
                } else {
                    continue;
                }
            }

            //获得收货地址信息
            $address_info = M('address')->where(array('id' => $this->__get['address_id'], 'customer_id' => $this->__seller_info['id']))->find();
            if ($address_info['city']) {
                $address_info['city'] = M('area')->where(array('id' => $address_info['city']))->getField('areaname');
            }
            $this->assign('address', $address_info);

            $this->assign('distribution', $distribution);
            $this->assign('supplys', $supplys);
            $this->assign('outh', $this->__get);
            $this->assign('info', $info);
            $this->display();
        }
    }

    /**
     * 获得分类商品属性
     */
    public function goodsCatAttrList() {
        $category_id = I('get.category_id') && intval(I('get.category_id')) > 0 ? I('get.category_id') : $this->error('信息错误');
        $goods_id = I('get.goods_id') && intval(I('get.goods_id')) > 0 ? I('get.goods_id') : 0;
        $data = '';
        //递归获取分类绑定的属性，一直往上，获取位置
        $this->_categoryBindAtr($category_id, $data);
        $html_str = '';
        if (!$data)
            $this->error('没有数据');
        //如果有商品ID则去获取商品信息绑定的属性
        $goods_attr_data = '';
        if ($goods_id > 0) {
            $goods_attr = M('goods_attribute')->where(array('goods_id' => $goods_id))->select();
            if ($goods_attr) {
                foreach ($goods_attr as $key => $value) {
                    $goods_attr_data[$value['attribute_id']] = $value['data'];
                }
            }
        }
        foreach ($data as $key => $value) {
            $html_str .= "<dl><dt>{$value['name']}：</dt><dd>";
            switch ($value['type']) {
                case '1' :
                    $html_str .= "<input type='text' value='" . ($goods_attr_data && $goods_attr_data[$value['id']] ? $goods_attr_data[$value['id']] : $value['default']) . "' name='goods_attr[{$value['id']}]' />";
                    break;
                case '2' :
                case '3' :
                case '4' :
                    $default_data = '';
                    if ($goods_attr_data && $goods_attr_data[$value['id']])
                        $default_data = explode(',', $goods_attr_data[$value['id']]);
                    if ($value['type'] == 4) {
                        $html_str .= "<select name='goods_attr[{$value['id']}]'>";
                        $attr_list = explode(',', $value['bute_val']);
                        foreach ($attr_list as $k => $v) {
                            $html_str .= "<option value='{$v}' " . ($value['default'] == $v || in_array($v, $default_data) ? 'selected' : '') . ">{$v}</option>";
                        }
                        $html_str .= "</select>";
                    } else {
                        $attr_list = explode(',', $value['bute_val']);
                        foreach ($attr_list as $k => $v) {
                            $html_str .= "<label><input type='" . ($value['type'] == 2 ? 'radio' : 'checkbox') . "' value='{$v}' " . ($value['default'] == $v && !$default_data || in_array($v, $default_data) ? 'checked' : '') . "  name='goods_attr[{$value['id']}]" . ($value['type'] == 2 ? '' : '[]') . "' /> {$v}</label>";
                        }
                    }
            }
            $html_str .= "</dd></dl>";
        }
        $this->success($html_str);
    }

    /**
     * 获取分类绑定的属性
     */
    private function _categoryBindAtr($cat_id, &$data) {
        $data = M('attribute')->where(array('category_id' => $cat_id))->select();
        if (!$data) {
            $category_info = M('goods_type')->find($cat_id);
            if ($category_info)
                $this->_categoryBindAtr($category_info['pid'], $data);
        }
    }

    /**
     * 商品详情
     */
    public function show() {
        if (!isset($this->__get['id']) || intval($this->__get['id']) <= 0)
            $this->error('信息错误');
        $goods_info = M('goods')->alias('g')->join('LEFT JOIN __GOODS_TYPE__ gt ON gt.id = g.goods_type_id')->where(array('g.id' => $this->__get['id']))->field('g.*,gt.name AS type_name')->find();
        $goods_info['pic_list'] = $goods_info['pic_list'] ? json_decode($goods_info['pic_list']) : '';
        $goods_info['is_distribution'] = M('goods_distribution')->where(array('customer_id' => $this->__seller_info['id'], 'goods_id' => $goods_info['id'], 'type' => 1))->find() ? 1 : 0;
        $goods_info['supply_total'] = M('goods_supply')->where(array('goods_id' => $this->__get['id'], 'status' => 2))->count();
        $goods_info['distribution_total'] = M('goods_distribution')->where(array('goods_id' => $this->__get['id']))->count();
        $this->assign('goods', $goods_info);
        $stock_num = M('goods_supply')->where(array('goods_id' => $this->__get['id'], 'stock_status' => 1))->sum('stock_num');
        $this->assign('stock_num', ($stock_num ? $stock_num : 0));
        $stock_num_send = M('goods_supply')->where(array('goods_id' => $this->__get['id'], 'stock_status' => 2))->sum('stock_num');
        $this->assign('stock_num_send', ($stock_num_send ? $stock_num_send : 0));
        $this->assign('attr_list', M('goods_attribute')->alias('ga')->join('__ATTRIBUTE__ a ON a.id = ga.attribute_id')->field('a.name,ga.data')->where(array('ga.goods_id' => $this->__get['id']))->select());
        $this->display();
    }

    //供货商品资料修改

    public function information() {
        $id = I('get.id');
        $m = M('goods_supply');
        if (IS_POST) {
            $data['information'] = serialize($this->__post['poster']['information']);
            if ($m->where(array('id' => $this->__post['poster']['id'], 'status' => array('lt', 2), 'customer_id' => $this->__seller_info['id']))->save($data)) {
                $this->success('修改资料成功，等待管理员审核！', U('supplyGoodsList'));
            } else {
                $this->error('修改失败');
            }
        } else {
            if ($info = $m->where(array('id' => $id, 'customer_id' => $this->__seller_info['id']))->find()) {
                $info['information'] = implode(',', unserialize($info['information']));
                $this->assign('info', $info);
                $this->display();
            } else {
                $this->error('信息错误');
            }
        }
    }

    function price() {
        $num = I('get.num');
        $supply_product_id = I('get.supply_product_id');
        $data['errno'] = 0;
        $data['msg'] = '失败';
        $prcie = wholesale_goods_price($supply_product_id, $num);
        if ($prcie > 0) {
            $data['errno'] = 1;
            $data['price'] = $prcie;
            $data['msg'] = '成功';
        }
        $this->ajaxReturn($data);
        die;
    }

    //付款方式修改
    public function paymentTypeSave() {
        if (IS_POST) {
            $submit_data = $this->__post['distribution'];
            isset($submit_data['id']) && intval($submit_data['id']) <= 0 ? $this->error('信息不全') : '';
            isset($submit_data['lock_pay_type']) && intval($submit_data['lock_pay_type']) <= 0 ? $this->error('信息不全') : '';
            isset($submit_data['wholesale_pay_type']) && intval($submit_data['wholesale_pay_type']) <= 0 ? $this->error('信息不全') : '';
            $submit_data['wholesale_pay_rule'] = $submit_data['wholesale_pay_type'] > 1 ? serialize($submit_data['wholesale_pay_rule']) : '';
            if ($submit_data['lock_pay_type'] == 1) {
                $lock_pay_rule = '';
            } else if ($submit_data['lock_pay_type'] == 2) {
                unset($submit_data['lock_pay_rule']['received']);
                $lock_pay_rule = serialize($submit_data['lock_pay_rule']);
            } else if ($submit_data['lock_pay_type'] == 3) {
                $lock_pay_rule = serialize($submit_data['lock_pay_rule']);
            }
            $submit_data['lock_pay_rule'] = $lock_pay_rule;
            M('goods_supply')->save($submit_data);
            $this->success('付款方式修改成功');
        } else {
            if (!isset($this->__get['id']) || intval($this->__get['id']) <= 0)
                $this->error('信息错误');
            $goods_supply = M('goods_supply')->find($this->__get['id']);
            $goods_supply['lock_pay_rule'] = $goods_supply['lock_pay_type'] == 1 ? '' : unserialize($goods_supply['lock_pay_rule']);
            $goods_supply['wholesale_pay_rule'] = $goods_supply['wholesale_pay_type'] == 1 ? '' : unserialize($goods_supply['wholesale_pay_rule']);
            $this->assign('data', $goods_supply);
            $this->display();
        }
    }

    //数据统计
    public function goodsSupplyCount() {
        if (!isset($this->__get['id']) || intval($this->__get['id']) <= 0)
            tipsDivError('信息错误');
        $info = M('goods_supply_count')->where(array('customer_id' => $this->__seller_info['id'], 'goods_supply_id' => $this->__get['id']))->find();
        if (!$info) {
            tipsDivError('信息不存在');
        }
        $this->assign('item', $info);
        $this->display();
    }

    //在途申请到在库

    public function application() {
        if (IS_POST) {
            $data = $this->__post;
            $data['piclist'] = implode(',', $data['piclist']);
            if (empty($data['piclist'])) {
                $this->error('请上传资料！');
                die;
            }
            $data['customer_id'] = $this->__seller_info['id'];
            $data['application_status'] = 0;
            if (M('goods_supply')->save($data)) {
                $this->success('申请已经发送，等待管理员确认', U('supplygoodslist'));
                die;
            } else {
                $this->error('申请失败，请重新申请');
                die;
            }
        }
        if (!isset($this->__get['id']) || intval($this->__get['id']) <= 0)
            exit('信息不存在');
        $info = M('goods_supply')->where(array('id' => $this->__get['id'], 'customer_id' => $this->__seller_info['id']))->find();
        if (!$info)
            $this->error('信息不存在');
        $this->assign('info', $info);
        $this->display('application');
    }

}
